package com.xqboss.apps.service.order.pay.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xqboss.apps.constant.YeepayConfig;
import com.xqboss.apps.domain.order.PayApply;
import com.xqboss.apps.dto.order.SignPayDto;
import com.xqboss.apps.dto.order.TradeResultDto;
import com.xqboss.apps.enums.order.OrderTypeEnum;
import com.xqboss.apps.enums.user.PayTypeEnum;
import com.xqboss.apps.service.order.pay.PayExecutor;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.ip.IpUtils;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.common.request.YopRequest;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component(value = PayTypeEnum.Code.YeePay_Alipay)
public class YeePayAlipayxecutor extends BaseYeePay {

    @Override
    public SignPayDto signPay(PayApply info) {
        YopRequest request = new YopRequest("/rest/v1.0/aggpay/pre-pay", "POST");
        request.addParameter("parentMerchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("merchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("orderId", info.getId());
        request.addParameter("orderAmount", info.getOrderAmount().toPlainString());
        request.addParameter("goodsName", "加油蛙-" + info.getSubject());
        if (info.getOrderType() != null && (info.getOrderType() == OrderTypeEnum.Market || info.getOrderType() == OrderTypeEnum.Gift)) {
            request.addParameter("fundProcessType", "DELAY_SETTLE");
        } else {
            request.addParameter("fundProcessType", "REAL_TIME");
        }
        request.addParameter("notifyUrl", yeepayConfig.getPayNotifyUrl());
        request.addParameter("expiredTime", info.getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//        request.addParameter("returnUrl", yeepayConfig.getPayReturnUrl());
        // 支付类型
        request.addParameter("channel", "ALIPAY");
        // 支付方式
        request.addParameter("payWay", "USER_SCAN");
        // 支付场景
        request.addParameter("scene", "OFFLINE");
        // 用户IP
        request.addParameter("userIp", IpUtils.getIpAddr());

        try {
            YopResponse response = yeepayConfig.getClient().request(request);
            Map<String, String> ret = (Map<String, String>) response.getResult();
            if("00000".equals(ret.get("code"))){
                SignPayDto dto = new SignPayDto();
                //易宝收款订单号
                dto.setOutTradeNo(ret.get("uniqueOrderNo"));
                //支付宝扫码链接
                String prePayTn = ret.get("prePayTn");
                // 组合跳转支付链接
                String url = URLEncodeUtil.encodeAll(prePayTn, StandardCharsets.UTF_8);
                String jumpPath = "alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + url;
                jumpPath = URLEncodeUtil.encodeAll(jumpPath, StandardCharsets.UTF_8);
                dto.setPayInfo(yeepayConfig.getAliPayJumpUrl() + jumpPath);
                return dto;
            }
            log.error("生成支付失败:request:{} - ret:{}", JSON.toJSONString(request), response.getStringResult());
            throw new ServiceException("支付失败，请重试");
        } catch (YopClientException e) {
            log.error("生成支付异常", e);
            throw new ServiceException("支付失败，请重试");
        }
    }
}
